package com.tanzeer.deliverytracker.fragments;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.tanzeer.deliverytracker.DeliveryListActivity;
import com.tanzeer.deliverytracker.MainActivity;
import com.tanzeer.deliverytracker.R;
import com.tanzeer.deliverytracker.TrackDetailsUIUpdaterInterface;
import com.tanzeer.deliverytracker.adapter.SpinnerItemAdapter;
import com.tanzeer.deliverytracker.dbhelper.RelsellDBOpenHelper;
import com.tanzeer.deliverytracker.models.RowItem;
import com.tanzeer.deliverytracker.models.RowItem.ActivitySummary;
import com.tanzeer.deliverytracker.utility.ApplicationVars;
import com.tanzeer.deliverytracker.utility.TrackerServiceClass;

public class TrackDetailsFragment extends Fragment implements TrackDetailsUIUpdaterInterface {

	

	private SharedPreferences mSharedpreferences;

	public static final String ARG_POSITION_TRACK = "position";

	public static String ARG_TYPE="type";

	public static String CATEGORY = "categoryName";
	
	String tappedPosition;
	ArrayList<String> spinnerItem = new ArrayList<String>();
	private TableRow mItemTableRow;
	private TableRow mActivityTableRow;
	private TableLayout mItemSummaryTable;
	private TableLayout mActivitySummaryTable;
	private String mType="";
	private String mCategory = "";
	private static final int BUTTON_POSITIVE = -1;
	private static final int BUTTON_NEGATIVE = -2;
	private View mLayoutView;
	private RowItem rItem;
	private LinearLayout mActivityErrorLayout;
	private TextView mActivityErrorTextView;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tappedPosition = TrackDetailsFragment.this.getArguments().getString(ARG_POSITION_TRACK);
		mType = TrackDetailsFragment.this.getArguments().getString(ARG_TYPE);
		mCategory = TrackDetailsFragment.this.getArguments().getString(CATEGORY);
		ApplicationVars.getInstance().setTrackDetailsCallback(this);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_track_details, null, false);
		mActivityErrorLayout = (LinearLayout)view.findViewById(R.id.errorTxtLayoutActivityInfo);
		mActivityErrorTextView = (TextView)view.findViewById(R.id.textView007);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mLayoutView  = view;
		startProcess(null,null);
	}
	public void startProcess(HashMap<String, String> trackIdAndStatus, String returnedRowData) {
		ArrayList<RowItem> list = ApplicationVars.getInstance().getTrackList();
		if(mType != null && mType.equalsIgnoreCase("Active")){
			list = ApplicationVars.getInstance().getTrackList();
		} else if(mType != null && mType.equalsIgnoreCase("Completed")) {
			list = ApplicationVars.getInstance().getCompletedTrackList();
		}
		
		
		rItem = null;
		for (RowItem localObj : list) {
			if(localObj.itemSummary._id.equalsIgnoreCase(tappedPosition)){
				rItem = localObj;
				break;
			}
		}
		
	
		mItemSummaryTable = (TableLayout) mLayoutView
				.findViewById(R.id.itemsummarytable);
		mActivitySummaryTable = (TableLayout) mLayoutView
				.findViewById(R.id.activitysummary);
		
		LayoutInflater li = (LayoutInflater) getActivity()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		if(mItemTableRow == null) {
		  mItemTableRow = (TableRow) li.inflate(R.layout.table_row, null);
		}

		
		
		ActionBar ac = getActivity().getActionBar();
		ac.setTitle(rItem.itemSummary.trackName);    // TODO: this is to be changed
				
		
		TextView one = (TextView) mItemTableRow
				.findViewById(R.id.textview1);
		one.setTextSize(10);
		one.setText(rItem.itemSummary.trackno);
		
		
		TextView two = (TextView) mItemTableRow
				.findViewById(R.id.textview2);
		two.setTextSize(10);
		two.setText(rItem.itemSummary.origin);
		TextView three = (TextView) mItemTableRow
				.findViewById(R.id.textview3);
		three.setTextSize(10);
		three.setText(rItem.itemSummary.destination);
		TextView four = (TextView) mItemTableRow
				.findViewById(R.id.textview4);
		four.setTextSize(10);
		four.setText(rItem.itemSummary.status);
		
		if(trackIdAndStatus == null) {		
		  mItemSummaryTable.addView(mItemTableRow);
		}
		
		if(mActivityTableRow == null) {
		mActivityTableRow = (TableRow) li.inflate(R.layout.table_row, null);
		}
		for(RowItem  localObj : rItem.getActivitySummaryItem(getActivity(), rItem.itemSummary)) {
			one = (TextView) mActivityTableRow
					.findViewById(R.id.textview1);
			one.setTextSize(10);
			String dataOne = localObj.activitySummary.dateTime;
			String[] dataOneArr = dataOne.split(" ");
			String[] timeArr = null;
			timeArr = dataOneArr[1].split(":");
			if (dataOneArr[2].equals("PM")) {
				timeArr[0] = "" + (Integer.parseInt(timeArr[0]) + 12);
				dataOneArr[1] = timeArr[0] + ":" + timeArr[1];
			} else {
				if (timeArr[0].length() < 2) {
					timeArr[0] = '0' + timeArr[0];
				}
				dataOneArr[1] = timeArr[0] + ":" + timeArr[1];
			}

			final String OLD_FORMAT = "MM/dd/yyyy";
			final String NEW_FORMAT = "dd.MM.yyyy";

			// August 12, 2010
			String oldDateString = dataOneArr[0];
			String newDateString = null;

			SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
			Date d = null;
			try {
				d = sdf.parse(oldDateString);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sdf.applyPattern(NEW_FORMAT);
			newDateString = sdf.format(d);

			one.setText(newDateString + " " + dataOneArr[1]);
			
			
		    two = (TextView) mActivityTableRow
					.findViewById(R.id.textview2);
			two.setTextSize(10);
			two.setText(localObj.activitySummary.activity);
			three = (TextView) mActivityTableRow
					.findViewById(R.id.textview3);
			three.setTextSize(10);
			three.setText(localObj.activitySummary.location);
			
			four = (TextView) mActivityTableRow
					.findViewById(R.id.textview4);
			four.setTextSize(10);
			
			
			if(!rItem.itemSummary.status.equalsIgnoreCase("Not Delivered")) {
			    String []splitArr = localObj.activitySummary.remarks.split(":");
			    int length = splitArr.length;
			    if(length == 2) {
				four.setText(splitArr[0]+"\n"+splitArr[1]);
			    } else {
			    	four.setText(splitArr[0]);
			    }
			}
			
		}
		if(trackIdAndStatus == null) {		
			  mActivitySummaryTable.addView(mActivityTableRow);
		}
		
		if (returnedRowData != null && !returnedRowData.equalsIgnoreCase("")) {
			mActivityErrorLayout.setVisibility(View.VISIBLE);
    		mActivityErrorTextView.setText(returnedRowData); 
		}
		
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		
		if(mType != null && mType.equalsIgnoreCase("Completed")) {
			inflater.inflate(R.menu.completed, menu);
		} else {
			inflater.inflate(R.menu.details, menu);
		}
		
	}
	
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.markpending) {
           
			RelsellDBOpenHelper rHelper = new RelsellDBOpenHelper(getActivity());
            
            ArrayList<RowItem> list = null;
			   if(mType != null && mType.equalsIgnoreCase("Completed")) {
	    			list = ApplicationVars.getInstance().getCompletedTrackList();
	    		}
	    		RowItem rItem = null;
	    		for (RowItem localObj : list) {
	    			if(localObj.itemSummary._id.equalsIgnoreCase(tappedPosition)){
	    				rItem = localObj;
	    				break;
	    			}
	    		}
	            
	    		rHelper.updatePackageDelivery(rItem,false);
	    		Intent intent=new Intent(getActivity(),DeliveryListActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra("type","Active");
				startActivity(intent);
				
		}else if (item.getItemId() == R.id.edit) {
			showEditTrackDialog();
		} else if (item.getItemId() == R.id.markc) {
            RelsellDBOpenHelper rHelper = new RelsellDBOpenHelper(getActivity());
            
            ArrayList<RowItem> list = ApplicationVars.getInstance().getTrackList();
    		if(mType != null && mType.equalsIgnoreCase("Active")){
    			list = ApplicationVars.getInstance().getTrackList();
    		} 
    		
    		
    		
    		RowItem rItem = null;
    		for (RowItem localObj : list) {
    			if(localObj.itemSummary._id.equalsIgnoreCase(tappedPosition)){
    				rItem = localObj;
    				break;
    			}
    		}
    		rHelper.updatePackageDelivery(rItem,true);
    		
			Intent intent=new Intent(getActivity(),DeliveryListActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("type",mType);
			startActivity(intent);
			 

		} else if (item.getItemId() == R.id.remove) {
			  ArrayList<RowItem> list = ApplicationVars.getInstance().getTrackList();
	    		if(mType != null && mType.equalsIgnoreCase("Active")){
	    			list = ApplicationVars.getInstance().getTrackList();
	    		} else if(mType != null && mType.equalsIgnoreCase("Completed")) {
	    			list = ApplicationVars.getInstance().getCompletedTrackList();
	    		}
	    		RowItem rItem = null;
	    		for (RowItem localObj : list) {
	    			if(localObj.itemSummary._id.equalsIgnoreCase(tappedPosition)){
	    				rItem = localObj;
	    				break;
	    			}
	    		}
	    		
			showDeleteDialog(rItem);

		} else if (item.getItemId() == R.id.shareit) {
			ArrayList<RowItem> list = ApplicationVars.getInstance().getTrackList();
    		if(mType != null && mType.equalsIgnoreCase("Active")){
    			list = ApplicationVars.getInstance().getTrackList();
    		} else if(mType != null && mType.equalsIgnoreCase("Completed")) {
    			list = ApplicationVars.getInstance().getCompletedTrackList();
    		}
    		RowItem rItem = null;
    		for (RowItem localObj : list) {
    			if(localObj.itemSummary.trackno.equalsIgnoreCase(tappedPosition)){
    				rItem = localObj;
    				break;
    			}
    		}
			Intent sendIntent = new Intent();
			sendIntent.setAction(Intent.ACTION_SEND);
			String constructData = rItem.itemSummary.toString() + "\n\nActivity Summary\n"+rItem.getActivitySummaryItem(getActivity(),rItem.itemSummary);
			sendIntent.putExtra(Intent.EXTRA_TEXT,constructData);
			sendIntent.setType("text/plain");
			startActivity(sendIntent);

		} else if (item.getItemId() == R.id.copy) {
			ArrayList<RowItem> list = ApplicationVars.getInstance().getTrackList();
    		if(mType != null && mType.equalsIgnoreCase("Active")){
    			list = ApplicationVars.getInstance().getTrackList();
    		} else if(mType != null && mType.equalsIgnoreCase("Completed")) {
    			list = ApplicationVars.getInstance().getCompletedTrackList();
    		}
    		RowItem rItem = null;
    		for (RowItem localObj : list) {
    			if(localObj.itemSummary.trackno.equalsIgnoreCase(tappedPosition)){
    				rItem = localObj;
    				break;
    			}
    		}
    		String constructData = rItem.itemSummary.toString() + "\n\nActivity Summary\n"+rItem.getActivitySummaryItem(getActivity(),rItem.itemSummary);
			copyToClipBoard(rItem.itemSummary.trackno);

		}

		return super.onOptionsItemSelected(item);
	}
	private void copyToClipBoard(String trackNo) {
		ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
		ClipData clip = ClipData.newPlainText("simple text", trackNo);
		clipboard.setPrimaryClip(clip);

	}

	private void showDeleteDialog(final RowItem rItem) {

		AlertDialog Alert = new AlertDialog.Builder(
				getActivity()).create();
		Alert.setTitle("Delete");
		Alert.setMessage("Want to remove this  delivery?");

		Alert.setButton(BUTTON_POSITIVE, "Remove",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						RelsellDBOpenHelper rHelper = new RelsellDBOpenHelper(getActivity());
						int res = rHelper.removeTrackNo(rItem);
						if(res == 1) {
						toast("Delivery Removed");
						Intent intent=new Intent(getActivity(),DeliveryListActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra("type",mType);
						intent.putExtra(CATEGORY,mCategory);
						startActivity(intent);
						}
					}
				});

		Alert.setButton(BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();

					}
				});
		Alert.show();
	}
	private void toast(String str) {
		Toast.makeText(getActivity(), str, Toast.LENGTH_LONG).show();
	}
	
	private void showEditTrackDialog() {
		
		ArrayList<RowItem> list = ApplicationVars.getInstance().getTrackList();
		if(mType != null && mType.equalsIgnoreCase("Active")){
			list = ApplicationVars.getInstance().getTrackList();
		} else if(mType != null && mType.equalsIgnoreCase("Completed")) {
			list = ApplicationVars.getInstance().getCompletedTrackList();
		}
		RowItem rItem = null;
		for (RowItem localObj : list) {
			if(localObj.itemSummary._id.equalsIgnoreCase(tappedPosition)){
				rItem = localObj;
				break;
			}
		}
		
		
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.addcontent);
		final EditText edtPkgNumber = (EditText) dialog
				.findViewById(R.id.editText1);
		final EditText edtPkgDescription = (EditText) dialog
				.findViewById(R.id.editText2);
		final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner1);
		setSpinnerItem();
		edtPkgNumber.setText(rItem.itemSummary.trackno);
		edtPkgDescription.setText(rItem.itemSummary.trackName);
		
		SpinnerItemAdapter adapter = new SpinnerItemAdapter(
				getActivity(), R.layout.spinner_row_view_custom,
				spinnerItem);
		spinner.setAdapter(adapter);
		
		int selectedPosition = -1;
		int i = 0;
		for(String str : spinnerItem) {
			if(str.equalsIgnoreCase(rItem.itemSummary.category)) {
				selectedPosition = i;
				break;
			}
			i++;
		}
		
		spinner.setSelection(selectedPosition);

		Button btnOk = (Button) dialog.findViewById(R.id.button2);
		Button btnCancel = (Button) dialog.findViewById(R.id.button1);
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String tracknumber = edtPkgNumber.getText().toString();
				String description = edtPkgDescription.getText().toString();
				String category = spinner.getSelectedItem().toString();
				String status = "NOT DELIVERED";
				if (!tracknumber.equals("") && !description.equals("")
						&& !category.equals("")) {
					if (ApplicationVars.getInstance().isSubscribed()) {
						RelsellDBOpenHelper dbHelper = new RelsellDBOpenHelper(
								getActivity());
						dbHelper.updatePackageDelivery(tracknumber, description, category, status);
						Intent intent=new Intent(getActivity(),DeliveryListActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra("type",mType);
						intent.putExtra(CATEGORY,mCategory);
						startActivity(intent);
						
					}
					dialog.dismiss();

				} else
					toast("Some fields are empty");

			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}
	
	private void setSpinnerItem() {
		spinnerItem.add("None");
		spinnerItem.add("Incoming");
		spinnerItem.add("Outgoing");
		spinnerItem.add("Favorite");
		spinnerItem.add("Movie");
		spinnerItem.add("Gift");
		spinnerItem.add("Heart");
		spinnerItem.add("Business");
		spinnerItem.add("Important");
		spinnerItem.add("Camera");
		spinnerItem.add("Clothes");
		spinnerItem.add("Computer");
		spinnerItem.add("Games");
		spinnerItem.add("Food Dishes");
		spinnerItem.add("Light");
		spinnerItem.add("Music");
		spinnerItem.add("Office Materials");
		spinnerItem.add("Paint");
		spinnerItem.add("Medicine");
		spinnerItem.add("Flowers");
		spinnerItem.add("Sports");
		spinnerItem.add("Tools");
	}

	@Override
	public void updateUIForList(HashMap<String, String> trackIdAndStatus, String returnedRowData) {
		startProcess(trackIdAndStatus,returnedRowData);
	}

}
